<?php

function win_observation_col_data_handler() {
  $args = func_get_args();
  $action = $args[0];
  switch ($action) {
    case 'suggestName':
      suggest_name($args[1], $args[2]);
      break;
    case 'getKingdoms':
      get_kingdoms();
      break;
    case 'getKingdomPhylums':
      get_kingdom_phylums($args[1]);
      break;
    case 'getPhylumClasses':
      get_phylum_classes($args[1]);
      break;
    case 'getClassOrders':
      get_class_orders($args[1]);
      break;
    case 'getOrderFamilies':
      get_order_families($args[1]);
      break;
    case 'getFamiliyGenuses':
      get_familiy_genuses($args[1]);
      break;
    case 'getGenusSpecies':
      get_genus_species($args[1]);
      break;
  }
}

function suggest_name($type, $str) {
  $matches = array();
  // searching in database, only name column
  
  $result = db_query_range("SELECT name FROM col2009ac_taxa WHERE LOWER(taxon) = LOWER('%s') AND LOWER(name) LIKE LOWER('%%%s%')", $type, $str, 0, 20);
  // found wrote into $matches
  while ($data = db_fetch_object($result)) {
    $matches[$data->name] = check_plain($data->name);
  }
  // return for JS
  print drupal_to_js($matches);
  // we don't need goto next PHP
  exit();
}

function get_kingdoms() {
  $matches = array();

  $result = db_query("SELECT record_id, name FROM col2009ac_taxa WHERE taxon = 'Kingdom'");
  while ($data = db_fetch_object($result)) {
    $matches[$data->record_id] = check_plain($data->name);
  }
  
  print drupal_to_js($matches);
  // we don't need goto next PHP
  exit();
}

function get_kingdom_phylums($kingdom_id) {
  get_child_taxa('Phylum', $kingdom_id);
}

function get_phylum_classes($phylum_id) {
  get_child_taxa('Class', $phylum_id);
}

function get_class_orders($class_id) {
  get_child_taxa('Order', $class_id);
}

function get_order_families($order_id) {
  get_child_taxa('Family', $order_id);
}

function get_familiy_genuses($family_id) {
  get_child_taxa('Genus', $family_id);
}

function get_genus_species($genus_id) {
  get_child_taxa('Species', $genus_id);
}

function get_child_taxa($type, $parent_id) {
  $matches = array();

  $result = db_query("SELECT record_id, name FROM col2009ac_taxa WHERE taxon = '%s' and parent_id = %d", array($type, $parent_id));
  while ($data = db_fetch_object($result)) {
    $matches[$data->record_id] = check_plain($data->name);
  }
  
  print drupal_to_js($matches);
  // we don't need goto next PHP
  exit();
}